package com.cj.databse;

import android.Manifest;
import android.app.Application;
import android.arch.persistence.room.Room;
import android.support.annotation.WorkerThread;

import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * Created by chenjian on 2019/5/31 13:27.
 */
public class DataBaseManager {
    private final Application mApplication;
    private AppDatabase database;
    private volatile static DataBaseManager manager;
    private Disposable disposable;

    private DataBaseManager(Application application) {
        mApplication = application;
    }

    public static DataBaseManager getManager(Application application) {
        if (manager == null) {
            synchronized (DataBaseManager.class) {
                if (manager == null) {
                    manager = new DataBaseManager(application);

                }
            }
        }
        return manager;
    }

    public void open() {
        if (database != null && database.isOpen()) {
            return;
        }
        database = Room.databaseBuilder(mApplication,
                AppDatabase.class, Constant.APP_DATABASE)
                .build();
    }

    public void closeDataBase() {
        if (database != null && database.isOpen()) {
            database.close();
        }

    }

    public void clearAllTables() {
        database.clearAllTables();
    }

    public static final String PAGE_NUM = "pageNum";
    public static final String NORMAL = "NORMAL";

    @WorkerThread
    public List<PersonBean> getPerson(Map<String, String> map) {

        int pageNum = 0;
        String s = map.get(PAGE_NUM);
        if (s != null) {
            try {
                pageNum = Integer.valueOf(s);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        boolean normal = true;
        String res = map.get(NORMAL);
        if (res != null) {
            try {
                normal = Boolean.valueOf(res);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return database.dao().getPersonByType(pageNum,normal);
        }
        return database.dao().getPersonByPage(pageNum);
    }

    @WorkerThread
    public List<PersonBean> getPerson(int pageNum) {

        return database.dao().getPersonByPage(pageNum);
    }

    @WorkerThread
    public List<PersonBean> getAllPerson() {

        return database.dao().getAllPerson();
    }

    @WorkerThread
    public void addPerson(List<PersonBean> person) {

        database.dao().insertPortrait(person);
    }


}
